namespace :db do
  
  desc "clone量表，生成新量表"
  task(:clone_survey => :environment) do
    #if ARGV[0] =~ /^(\w+)=(.*)$/
    survey_id = 83

    Survey.transaction do
      survey = Survey.find survey_id
      s_clone = survey.clone
      s_clone.name = s_clone.name + " 副本"
      s_clone.save

      if survey.has_part == 1
        #clone parts
        survey.parts.each do |part|
          p_clone = part.clone
          p_clone.survey_id = s_clone.id
          p_clone.save

          #clone questions
          part.questions.each do |q|

            q_clone = q.clone
            q_clone.part_id = p_clone.id
            q_clone.survey_id = s_clone.id
            q_clone.save
            #clone choices
            q.choices.each do |c|
              c_clone = c.clone
              c_clone.question_id = q_clone.id
              c_clone.save
            end
          end
        end
      else
        #clone questions
        survey.questions.each do |q|
          q_clone = q.clone
          q_clone.survey_id = s_clone.id
          q_clone.save
          #clone choices
          q.choices.each do |c|
            c_clone = c.clone
            c_clone.question_id = q_clone.id
            c_clone.save
          end
        end
      end

      #clone dimens
      survey.dimens.each do |d|
        d_clone = d.clone
        d_clone.survey_id = s_clone.id
        d_clone.save
      end

      #clone norm_info
      n_clone = survey.norm_info.clone
      n_clone.survey_id = s_clone.id
      n_clone.save
    end
      
    #end
  end
end